<?php

namespace App\Http\Controllers;

use App\Http\Resources\NftDetailResource;
use App\Http\Resources\NftResource;
use App\Models\Nft;
use Illuminate\Http\Request;
use Symfony\Component\HttpKernel\Exception\HttpException;

class NftsController extends Controller
{
    public function index(Request $request)
    {
        $sortMode = $request->input('sort_mode', 'asc');
        $sortMode = $sortMode == 'asc' ? 'desc' : 'asc';

        $status = $request->input('status');
        $address = $request->input('address');
        $nfts = Nft::where('user_id', auth()->id())
            ->when($address, function ($query) use ($address) {
                $query->where('nft_id', $address);
            })
            ->orderBy('percent', $sortMode)
            ->when($status, function ($query) use ($status) {
                if ($status == 'working') {
                    $query->whereRaw('minted_days < days');
                } else {
                    $query->whereRaw('minted_days >= days');
                }
            })
            ->get();
        return NftResource::collection($nfts);
    }

    public function detail(Request $request)
    {
        $nftID = $request->input('nft_id');
        $nft = Nft::where('id', $nftID)->where('user_id', auth()->id())->first();
        if (!$nft) {
            throw new HttpException(404, 'NFT not found');
        }
        return new NftDetailResource($nft);
    }
}
